package com.fenghongzhang.yuekao;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;


/**
 * A simple {@link Fragment} subclass.
 */
public class TwoFragment extends Fragment {
    private TextView fgTime;
    private Button send;

    private int index = 5;
    private Timer timer;
    private static final String TAG = "TwoFragment";
    public Handler handler = new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Log.i(TAG, "handleMessage: ");

            if (msg.what == 110){
                if(timer == null){ //1次
                    timer = new Timer(); //2
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            handler.sendEmptyMessage(120);
                        }
                    },0,1000);
                }
            }else if (msg.what ==120){
                fgTime.setText("倒计时:"+index--+"秒");
                if(index <= 0){
                    timer.cancel();
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    startActivity(intent);
                    getActivity().finish();
                }
            }
        }
    };

    public TwoFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_two, container, false);

        fgTime = (TextView) inflate.findViewById(R.id.fg_time);
        send = (Button) inflate.findViewById(R.id.send);


        //点击跳转
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.cancel();
                Intent intent = new Intent(getActivity(), MainActivity.class);
                startActivity(intent);
                getActivity().finish();
            }
        });

        return inflate;
    }
}
